package com.yulp.springboot2task.service;

import com.yulp.springboot2task.constant.RetryMessageConstant;
import net.greghaines.jesque.Job;
import net.greghaines.jesque.client.ClientPoolImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 是否可以将该抽象方法做成一个公共类；job包..
 */
@Component
public abstract class RetryMessageSender {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ClientPoolImpl jesqueClientPool;

    private String queueName;

    private static final int[] RETRY_DELAY = new int[] { 5, 30, 60, 300, 600, 3600, 14400 };

    // retryMessageSender.setQueueName(....);
    // RetryMessageConstant.RetryMessageEnum.grfApply2cn.getQueueName();
    public void setQueueName(String queueName) {
        this.queueName = queueName;
    }

    public void sendDelayedEnqueue(String topic, String message, int retries) {
        RetryMessageConstant.RetryMessageEnum retryMessageEnum =
                RetryMessageConstant.RetryMessageEnum.getByQueueName(queueName);
        // -1 为永久执行
        if (retryMessageEnum.getMaxRetries() != -1 && retries >= retryMessageEnum.getMaxRetries()) {
            logger.error("send to delay queue end {} -{} -{}", topic, message, retries);
            retryDelayedEnqueueFinish(topic, message, retries);
            return;
        }

        //final long future = System.currentTimeMillis() + (RETRY_DELAY[retries] * 1000); // timestamp

        final long future = System.currentTimeMillis() + (retryMessageEnum.getRetryDelay()[retries] * 1000);
        final Job job = new Job(retryMessageEnum.getClassName(), topic, message, retries + 1, future + "");
        jesqueClientPool.delayedEnqueue(retryMessageEnum.getQueueName(), job, future);
        logger.info("send to delay queue {} -{} -{}", topic, message, retries);

    }

    // 结束时可作一些日志记录之类的。
    public abstract void retryDelayedEnqueueFinish(String topic, String message, int retries);
}
